package com.ruoyi.web.controller.blog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.NoteLike;
import com.ruoyi.system.domain.NoteFavorite;
import com.ruoyi.system.domain.NoteComment;
import com.ruoyi.system.service.INoteLikeService;
import com.ruoyi.system.service.INoteFavoriteService;
import com.ruoyi.system.service.INoteCommentService;

/**
 * 博客用户交互功能Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/blog/interaction")
public class BlogInteractionController extends BaseController
{
    @Autowired
    private INoteLikeService noteLikeService;

    @Autowired
    private INoteFavoriteService noteFavoriteService;

    @Autowired
    private INoteCommentService noteCommentService;

    /**
     * 切换点赞状态
     */
    @PostMapping("/like/toggle")
    public AjaxResult toggleLike(@RequestBody Map<String, Object> params)
    {
        Long userId = Long.valueOf(params.get("userId").toString());
        String noteType = params.get("noteType").toString();
        Long noteId = Long.valueOf(params.get("noteId").toString());

        boolean isLiked = noteLikeService.toggleLike(userId, noteType, noteId);
        int likeCount = noteLikeService.countLikesByNote(noteType, noteId);

        Map<String, Object> result = new HashMap<>();
        result.put("isLiked", isLiked);
        result.put("likeCount", likeCount);

        return AjaxResult.success("操作成功", result);
    }

    /**
     * 检查点赞状态
     */
    @Anonymous
    @GetMapping("/like/status")
    public AjaxResult getLikeStatus(@RequestParam Long userId, 
                                   @RequestParam String noteType, 
                                   @RequestParam Long noteId)
    {
        boolean isLiked = noteLikeService.isLiked(userId, noteType, noteId);
        int likeCount = noteLikeService.countLikesByNote(noteType, noteId);

        Map<String, Object> result = new HashMap<>();
        result.put("isLiked", isLiked);
        result.put("likeCount", likeCount);

        return success(result);
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/favorite/toggle")
    public AjaxResult toggleFavorite(@RequestBody Map<String, Object> params)
    {
        Long userId = Long.valueOf(params.get("userId").toString());
        String noteType = params.get("noteType").toString();
        Long noteId = Long.valueOf(params.get("noteId").toString());
        String folderName = params.getOrDefault("folderName", "默认收藏夹").toString();

        boolean isFavorited = noteFavoriteService.toggleFavorite(userId, noteType, noteId, folderName);
        int favoriteCount = noteFavoriteService.countFavoritesByNote(noteType, noteId);

        Map<String, Object> result = new HashMap<>();
        result.put("isFavorited", isFavorited);
        result.put("favoriteCount", favoriteCount);

        return AjaxResult.success("操作成功", result);
    }

    /**
     * 检查收藏状态
     */
    @Anonymous
    @GetMapping("/favorite/status")
    public AjaxResult getFavoriteStatus(@RequestParam Long userId, 
                                       @RequestParam String noteType, 
                                       @RequestParam Long noteId)
    {
        boolean isFavorited = noteFavoriteService.isFavorited(userId, noteType, noteId);
        int favoriteCount = noteFavoriteService.countFavoritesByNote(noteType, noteId);

        Map<String, Object> result = new HashMap<>();
        result.put("isFavorited", isFavorited);
        result.put("favoriteCount", favoriteCount);

        return success(result);
    }

    /**
     * 添加评论
     */
    @PostMapping("/comment/add")
    public AjaxResult addComment(@RequestBody NoteComment noteComment)
    {
        // 参数校验
        if (noteComment.getUserId() == null)
        {
            return error("用户ID不能为空");
        }
        if (StringUtils.isEmpty(noteComment.getNoteType()))
        {
            return error("笔记类型不能为空");
        }
        if (noteComment.getNoteId() == null)
        {
            return error("笔记ID不能为空");
        }
        if (StringUtils.isEmpty(noteComment.getContent()))
        {
            return error("评论内容不能为空");
        }

        // 设置默认值
        if (noteComment.getParentId() == null)
        {
            noteComment.setParentId(0L);
        }
        noteComment.setStatus("0");
        noteComment.setLikeCount(0L);

        int result = noteCommentService.insertNoteComment(noteComment);
        if (result > 0)
        {
            return success("评论成功");
        }
        else
        {
            return error("评论失败");
        }
    }

    /**
     * 获取评论列表
     */
    @Anonymous
    @GetMapping("/comment/list")
    public AjaxResult getCommentList(@RequestParam String noteType, 
                                    @RequestParam Long noteId,
                                    @RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "10") Integer pageSize)
    {
        List<NoteComment> comments = noteCommentService.selectCommentsByNote(noteType, noteId);
        int commentCount = noteCommentService.countCommentsByNote(noteType, noteId);

        Map<String, Object> result = new HashMap<>();
        result.put("comments", comments);
        result.put("total", commentCount);

        return success(result);
    }

    /**
     * 获取用户点赞的笔记列表
     */
    @GetMapping("/like/user-likes")
    public AjaxResult getUserLikes(@RequestParam Long userId)
    {
        List<NoteLike> likes = noteLikeService.selectUserLikedNotes(userId);
        return success(likes);
    }

    /**
     * 获取用户收藏的笔记列表
     */
    @GetMapping("/favorite/user-favorites")
    public AjaxResult getUserFavorites(@RequestParam Long userId)
    {
        List<NoteFavorite> favorites = noteFavoriteService.selectUserFavoriteNotes(userId);
        return success(favorites);
    }

    /**
     * 获取用户收藏夹列表
     */
    @GetMapping("/favorite/folders")
    public AjaxResult getUserFolders(@RequestParam Long userId)
    {
        List<String> folders = noteFavoriteService.selectUserFolders(userId);
        return success(folders);
    }

    /**
     * 根据收藏夹获取收藏列表
     */
    @GetMapping("/favorite/by-folder")
    public AjaxResult getFavoritesByFolder(@RequestParam Long userId, 
                                          @RequestParam String folderName)
    {
        List<NoteFavorite> favorites = noteFavoriteService.selectFavoritesByFolder(userId, folderName);
        return success(favorites);
    }

    /**
     * 获取用户评论列表
     */
    @GetMapping("/comment/user-comments")
    public AjaxResult getUserComments(@RequestParam Long userId)
    {
        List<NoteComment> comments = noteCommentService.selectUserComments(userId);
        return success(comments);
    }

    /**
     * 获取笔记的统计信息
     */
    @Anonymous
    @GetMapping("/stats")
    public AjaxResult getNoteStats(@RequestParam String noteType, 
                                  @RequestParam Long noteId,
                                  @RequestParam(required = false) Long userId)
    {
        Map<String, Object> stats = new HashMap<>();
        
        // 点赞数和状态
        int likeCount = noteLikeService.countLikesByNote(noteType, noteId);
        stats.put("likeCount", likeCount);
        
        // 收藏数和状态
        int favoriteCount = noteFavoriteService.countFavoritesByNote(noteType, noteId);
        stats.put("favoriteCount", favoriteCount);
        
        // 评论数
        int commentCount = noteCommentService.countCommentsByNote(noteType, noteId);
        stats.put("commentCount", commentCount);
        
        // 如果提供了用户ID，返回用户的交互状态
        if (userId != null)
        {
            boolean isLiked = noteLikeService.isLiked(userId, noteType, noteId);
            boolean isFavorited = noteFavoriteService.isFavorited(userId, noteType, noteId);
            
            stats.put("isLiked", isLiked);
            stats.put("isFavorited", isFavorited);
        }

        return success(stats);
    }
}